package cn.csg.ams.collect2.poptopics.task;

import cn.csg.ams.collect2.poptopics.dao.MkPrPfOutageRecoveryMonDao;
import cn.csg.ams.collect2.poptopics.infrastructure.utils.RedisLockUtil;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 损失负荷计算任务，每5分钟执行一次
 */
@Component
public class LossLoadTask {

    private static Logger logger = LoggerFactory.getLogger(LossLoadTask.class);

    @Autowired
    private MkPrPfOutageRecoveryMonDao outageRecoveryMonDao;

    @Autowired
    private RedisLockUtil redisLockUtil;


    // @Scheduled(cron = "0 0/5 * * * ?")
    public void lossLoadTask() {
        // 由于多节点部署，需要保证每次只有一个节点执行
        String key = "fbs_loss_load";
        String requestId = UUID.randomUUID().toString();
        boolean lock = redisLockUtil.lock(key, requestId, 120 * 1000);
        if (!lock) {
            logger.info("该节点未抢到锁，跳过损失负荷计算任务");
            return;
        }

        // 执行线路停电任务
        logger.info("节点抢到锁, 开始执行损失负荷计算任务.............");
        lossLoad();
    }


    private void lossLoad() {
        Date date = new Date();
        String outageStartTime = new SimpleDateFormat("yyyy-MM-dd").format(date);
        int dataPart = Integer.parseInt(new SimpleDateFormat("yyyyMMdd").format(date));
        int yesterdayDataPart = dataPart - 1;
        outageRecoveryMonDao.updateLossLoad(outageStartTime, dataPart, yesterdayDataPart);
    }

}
